package com.zhiy.com.estation.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

/**
 * All Resered by My Zong  @2016-2017
 * 该类封装合同谈判的get和post请求获取字符串，以及图片的上传和下载
 */
public class HttpTools {
    /**
     * 通过path获取网络请求字符串结果
     */
    public static String get(String path) {
        String result = "";
        Log.e("--------", "get方式请求的网址是： " + path);
        HttpURLConnection conn = null;
        InputStream is = null;

        try {
//         1、定位网络资源，声明访问网址
            URL url = new URL(path);
//            2、通过url对象获取连接http的连接
            conn = (HttpURLConnection) url.openConnection();
//            3、判断服务器返回码
            int code = conn.getResponseCode();
//            访问成功
            if (code == 200) {
//                4、通过连接输入流获取服务器返回的结果
                is = conn.getInputStream();
//                将inputstream转化成bufferReader，bufferReader可以直接读取字符串
                InputStreamReader isReader = new InputStreamReader(is);
                BufferedReader bufferedReader = new BufferedReader(isReader);
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
            } else {
                result = "" + "连接服务器失败，状态码： " + code;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
//                    关闭流
                    is.close();
                if (conn != null)
                    conn.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.d("------------", "get 方式请求的结果是： " + result);
        return result;
    }

    /**
     * post方法必须传递path过来
     * ，后边要传递的参数个数任意
     *
     * @param path
     * @param map
     * @return
     */
    public static String post(String path, Map<String, String> map) {
        String result = "";

        Log.d("---------", "post方式请求的网址是： " + path);
        HttpURLConnection conn = null;
        InputStream is = null;

        try {
//            1、定位网络资源，声明访问的网址
            URL url = new URL(path);
//            2、通过url对象获取连接http的连接
            conn = (HttpURLConnection) url.openConnection();
//          在get方式的基础上增加post代码
//            post:声明post方式，允许输入输出，获取连接的输出流，将post参数写入输出流
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
//           格式为key=value%key=value
            StringBuffer data = new StringBuffer();
//            遍历map集合拼接post参数
            for (String key : map.keySet()) {
                data.append(key).append("==")
                        .append(URLEncoder.encode(map.get(key), "UTF-8"))
                        .append("&");
            }
//            key=value&key=value&可去除尾部的&符号
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(data.toString());
            dos.flush();
//            3、判断服务器返回状态码
            int code = conn.getResponseCode();
            if (code == 200) {
//            4、通过连接的输入流获取服务器的返回结果
                is = conn.getInputStream();
//                将inputstream转化成bufferdReader，bufferReader 可以直接读取字符串
                InputStreamReader isReader = new InputStreamReader(is);
                BufferedReader bufferedReader = new BufferedReader(isReader);
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
            } else {
                result = "连接服务器失败，状态码 " + code;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
                if (conn != null)
                    conn.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.d("----------", "post方式请求的结果是" + result);
        return result;
    }

    /**
     * 上传文件到服务器，一般用于上传头像，参数是我们要上传的文件
     * 返回值是服务器存储文件的路径
     */
    public static String uploadFile(String path, File file) {
        Log.e("-----------", "开始上传文件");
        /**
         * 文件上传相关变量---边界值
         */
        String twoHyphens = "---";
//        边界标识，随机生成
        String boundary = UUID.randomUUID().toString();
        String end = "\r\n";

        String result = "";
        HttpURLConnection conn = null;
        InputStream is = null;
        try {
            URL url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();
            /**
             * 上传文件的步骤
             * post方式，允许输入输出，不允许缓存
             */
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);

//            文件上传的参数配置
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type",
                    "multipart/from-data;boundary=" + boundary);
//            拿到连接的数据输出流，将上传文件信息以及文件本体写入http中
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
//            文件边界
            dos.writeBytes(twoHyphens + boundary + end);
//            写文件信息
            dos.writeBytes("Content-Disposition: form-data;name=\"files\";filename=\"" + file.getName() + "\"" + end);
            dos.writeBytes("Content-Type:application/octet-stream;charset=utf-8" + end);
            dos.writeBytes(end);
            Log.d("-------", "上传文件的文件是--" + file.getName());
//            写入文件本体
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int length = -1;
            while ((length = fis.read(bytes)) != -1) {
                dos.write(bytes, 0, length);
            }
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + end);
            dos.flush();
            dos.close();

            int code = conn.getResponseCode();
            Log.d("-----------", "服务器返回的状态码是---" + code);
            if (code == 200) {
                is = conn.getInputStream();
                InputStreamReader isReader = new InputStreamReader(is);
                BufferedReader bufferedReader = new BufferedReader(isReader);
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
            } else {
                result = "连接服务器失败 " + code;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
                if (conn != null)
                    conn.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Log.d("--------", "上传文件的结果--" + result);
        return result;
    }

    /**
     * 下载图片
     */
    public static Bitmap getImageFromServer(String path) {
        Bitmap bitmap = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        Log.d("------", "下载图片，地址是：" + path);
        try {
            URL url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();

            if (conn.getResponseCode() == 200) {
                Log.d("------------", "连接服务器成功，状态码200");
                is = conn.getInputStream();
//                将一个输入流转化为图片
                bitmap = BitmapFactory.decodeStream(is);
            } else {
                Log.d("--------", "连接服务器失败，状态码： " + conn.getResponseCode());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
                if (conn != null)
                    conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }
}
